#! /bin/bash

all_op_names=("ThreeNN" "Cumsum" "ReduceSum" "GlobalAvgPool" "Lerp" "Histogram" "AsStrided" "Tril" "Gelu" "Triu" 
              "Mish" "MishGrad" "Dawsn" "Xlogy" "eye")

function convert_to_underline() {
    local input_string="$1"
    if [ "$input_string" = "ThreeNN" ]; then
        input_string="ThreeNn"
    fi
    local output_array=($(echo "$input_string" | sed 's/\([A-Z]\)/\ \1/g'))

    local result=""
    for i in "${output_array[@]}"; do
        lower_temp=$(echo "${i%% }" | tr '[:upper:]' '[:lower:]')

        if [[ -n $result ]]; then
            result+="_"
        fi
        result+="${lower_temp}"
    done

    echo "${result}"
}

function gen_single_op() {
    local upper_op_name="$1"
    local lower_op_name="$(convert_to_underline $upper_op_name)"
    msopgen gen -i ./op_jsons/${lower_op_name}.json -c ai_core-Ascend310B -lan cpp -out ${upper_op_name}
    sed -i "3a\export ASCEND_GLOBAL_LOG_LEVEL=0" ./${upper_op_name}/build.sh
    sed -i "3a\export ASCEND_SLOG_PRINT_TO_STDOUT=0" ./${upper_op_name}/build.sh
    sed -i "s/\/Ascend\/latest/\/Ascend\/ascend-toolkit\/latest/g" ./${upper_op_name}/CMakePresets.json
    sed -i "s/ascend310b/ascend910b/g" ./${upper_op_name}/CMakePresets.json
    sed -i "s/ascend310b/ascend910b/g" ./${upper_op_name}/op_host/${lower_op_name}.cpp
}

if [ -z "$1" ]; then
    for upper_op_name in "${all_op_names[@]}"; do
        if [ ! -d "${upper_op_name}" ]; then
            gen_single_op "$upper_op_name"
        fi
    done
else
    rm -rf $1
    gen_single_op "$1"
fi